package com.jala.base;

import com.alibaba.fastjson.JSONArray;
import com.jala.ecs.client.auth.Principal;
import com.jala.ecs.client.auth.model.User;
import com.jala.ecs.client.codedict.client.CodeDictClient;
import com.jala.ecs.client.codedict.model.CodeDictItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
public class CommonToolsAction{


    @Autowired
    private CodeDictClient codeDictClient;


    @Autowired
    private Principal principal;

    public String getUserName(Integer userId) {
        if(userId==null){
            return "";
        }
        User user= principal.getUser(userId);
        return user==null?"":user.getUserName();
    }


    /***
     *
     * object转json
     *
     */
    public String objToJson(Object obj) {
        return JSONArray.toJSONString(obj) ;
    }


    /***
     * 获取数据列的数值集合
     *
     * @param codeKey
     * @return
     */
    public List<CodeDictItem> getCodeDicts(String codeKey) {
        List<CodeDictItem>  resp = codeDictClient.getCodeDict(codeKey);
        return resp;
    }

    /***
     * 获取数据列的分组数值集合
     *
     * @param codeKey
     * @return
     */
    public List<CodeDictItem> getCodeDicts(String codeKey, String group) {
        List<CodeDictItem>  resp = codeDictClient.getCodeDict(codeKey, 1, group);
        return resp;
    }

    /***
     * 获取数据列的对象
     *
     * @param codeKey
     * @return
     */
    public CodeDictItem getCodeDict(String codeKey, String codeValue) {
        CodeDictItem resp = codeDictClient.getCodeDictItem(codeKey, codeValue);
        return resp;
    }

    /***
     * 获取数据列的名称
     *
     * @param codeKey
     * @return
     */
    public String getCodeDictName(String codeKey, String codeValue) {
        CodeDictItem resp = codeDictClient.getCodeDictItem(codeKey, codeValue);
        if(resp!=null){
            return resp.getCodeName();
        }
        return null;
    }

    /**
     * 判断当前业务code是否属于数据组权限
     *
     * @param dataGroupId
     *            数据组ID
     * @param code
     *            业务code
     * @return 一个hashTable，key为数据ID，value为数据的名称
     */
    public boolean isHasDataRights(String dataGroupId, String code) {
        return principal.isPermitted(dataGroupId,code);
    }

    /**
     * 判断当前用户的功能权限
     *
     * @param functionKey
     *            功能权限的key值
     * @return
     */
    public boolean isHasRights(String functionKey) {
        if (StringUtils.isEmpty(functionKey)){
            return false;
        }
        return principal.isPermitted(functionKey);
    }
    
    /**
	 * 获取指定长度字符串，超过部分用省略号表示
	 * 
	 * @param content
	 * @param len
	 * @return
	 */
	public String substr(String content, int len) {
		if (StringUtils.isEmpty(content) || content.length() <= len) {
			return content;
		} else {
			return content.substring(0, len) + "......";
		}
	}
}
